import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../providers/local_shared_cache.dart';
import '../../providers/user_context.dart';
import '../../utils/HttpUtil.dart';
import '../root_page.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _formKey = GlobalKey<FormState>();
  bool _obscureText = true;

  String _username = '';
  String _password = '';
  String _phoneNum = '';

  void _register() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      HttpUtil.getInstance()
          .post('/api/user/v1/register',
              data: jsonEncode({
                'username': _username,
                'password': _password,
                'phoneNum': _phoneNum
              }))
          .then((value) {
        var setCookie = value?.headers['authorization'];
        if (setCookie != null) {
          LocalSharedCache.saveString("authorization", jsonEncode(setCookie));
        }
        if (value!.data['data'] != null) {
          LocalSharedCache.saveString(
              "loginUid", jsonEncode(value!.data['data']));
          UserContext.fromJson(value!.data['data']);
        }
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (context) => HomePage()));
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(),
        title: const Text(
          '注册信息',
          style: TextStyle(color: Colors.blue),
        ),
      ),
      body: Container(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    margin: EdgeInsets.only(bottom: 10),
                    child: const Text(
                      "账号名称",
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                  TextFormField(
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: Colors.blue.shade100,
                      hintText: '名称',
                      border: OutlineInputBorder(
                        gapPadding: 0,
                        borderSide: BorderSide(
                          color: Colors.blue.shade100,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入用户名';
                      }
                      return null;
                    },
                    onSaved: (value) => _username = value!,
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: 10),
                    child: const Text(
                      "手机号",
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                  TextFormField(
                    keyboardType: TextInputType.phone,
                    inputFormatters: [
                      LengthLimitingTextInputFormatter(11),
                      FilteringTextInputFormatter.digitsOnly,
                    ],
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: Colors.blue.shade100,
                      hintText: '手机号',
                      border: OutlineInputBorder(
                        gapPadding: 0,
                        borderSide: BorderSide(
                          color: Colors.blue.shade100,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入手机号';
                      }
                      return null;
                    },
                    onSaved: (value) => _phoneNum = value!,
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: 10),
                    child: const Text(
                      "密码",
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                  TextFormField(
                    obscureText: _obscureText,
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: Colors.blue.shade100,
                      hintText: '密码',
                      suffixIcon: IconButton(
                        icon: Icon(_obscureText
                            ? Icons.visibility
                            : Icons.visibility_off),
                        onPressed: () {
                          setState(() {
                            _obscureText = !_obscureText;
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入密码';
                      }
                      return null;
                    },
                    onSaved: (value) => _password = value!,
                  ),
                ],
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            SizedBox(
              width: 200,
              child: FilledButton(
                onPressed: () {
                  _register();
                },
                style: FilledButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.blue,
                ),
                child: const Text('注册'),
              ),
            ),
            const Text('三方注册'),
            Wrap(
              children: [
                IconButton(
                    onPressed: () {},
                    icon: Icon(
                      Icons.access_time,
                      size: 40,
                    )),
                IconButton(
                    onPressed: () {},
                    icon: Icon(
                      Icons.access_time,
                      size: 40,
                    )),
                IconButton(
                    onPressed: () {},
                    icon: Icon(
                      Icons.access_time,
                      size: 40,
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
